package com.plan.service.uesr.impl;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.plan.base.constant.Constant;
import com.plan.base.util.jwt.JwtUtil;
import com.plan.controller.user.response.MenuPackageVO;
import com.plan.controller.user.response.UserVO;
import com.plan.dao.mapper.user.MenuMapper;
import com.plan.dao.mapper.user.PackageMenuMapper;
import com.plan.dao.mapper.user.UserMapper;
import com.plan.dao.mapper.user.UserPackageMapper;
import com.plan.entity.user.User;
import com.plan.entity.user.UserPackage;
import com.plan.service.uesr.AuthManager;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AuthManagerImpl implements AuthManager {
    @Resource
    private JwtUtil jwt;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserPackageMapper userPackageMapper;
    @Resource
    private PackageMenuMapper packageMenuMapper;

    /**
     * 缓存用户信息
     */
    private LoadingCache<Long, UserVO> userCache;

    /**
     * Map的key为url，value为packageId
     */
    private LoadingCache<String, Map<String, Integer>> urlPackageIdCache;

    @PostConstruct
    public void init() {
        // 购买之后，要清空
        userCache = CacheBuilder.newBuilder()
                .expireAfterWrite(24, TimeUnit.HOURS)
                .build(new CacheLoader<Long, UserVO>() {
                    @Override
                    public UserVO load(Long userId) {
                        User user = userMapper.selectOneById(userId);
                        List<UserPackage> packages = userPackageMapper.selectUserPackages(userId);
                        UserVO vo = new UserVO();
                        BeanUtils.copyProperties(user, vo);
                        vo.setPackages(packages);
                        return vo;
                    }
                });
        urlPackageIdCache = CacheBuilder.newBuilder()
                .expireAfterWrite(24, TimeUnit.HOURS)
                .build(new CacheLoader<String, Map<String, Integer>>() {
                    @Override
                    public Map<String, Integer> load(String key) {
                        List<MenuPackageVO> list = packageMenuMapper.selectUrlPackageId();
                        if (list == null) {
                            return new HashMap<>(0);
                        }
                        return list.stream().collect(Collectors.toMap(MenuPackageVO::getUrl, MenuPackageVO::getPackageId, (k1, k2) -> k1));
                    }
                });
    }


    @Override
    public String creatToken(User user) {
        String token = null;
        try {
            token = jwt.createToken(String.valueOf(user.getId()));
        } catch (Exception e) {
            log.error("creatToken error", e);
        }
        return token;
    }

    @Override
    public UserVO getUserForToken(HttpServletRequest request) {
        String token = request.getHeader(Constant.TOKEN_NAME);
        return getUserForToken(token);
    }

    @Override
    public UserVO getUserForToken(String token) {
        Claims claims = jwt.extractAllClaims(token);
        Long userId = Long.parseLong(claims.getSubject());
        try {
            return userCache.get(userId);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public UserVO getUserByIdFromCache(Long userId) {
        try {
            return userCache.get(userId);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean isExpiration(String token) {
        try {
            return jwt.isTokenExpired(token);
        } catch (Exception e) {
//            log.error("isExpiration error", e);
            return true;
        }
    }

    @Override
    public Integer getPackageId(String uri) {
        try {
            Map<String, Integer> map = urlPackageIdCache.get("allUrlPackageId");
            return map.get(uri);
        } catch (ExecutionException e) {
            log.error("getPackageId error", e);
            return null;
        }
    }

    @Override
    public void clearUser(Long userId) {
        userCache.invalidate(userId);
    }

}
